/**
 * 
 */
package com.alstudio.core.iaj;

import android.graphics.Color;
import android.text.Html;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.URLSpan;
import android.widget.TextView;

/**
 * 应用内跳转管理器
 * 
 * @author alonso lee
 * 
 */
public class ALIAppJumpManager implements ALUrlClickListener {

	private static ALIAppJumpManager instance;

	public static ALIAppJumpManager getIAppJumpManager() {
		if (instance == null) {
			instance = new ALIAppJumpManager();
		}
		return instance;
	}

	/**
	 * 设置跳转文案
	 * 
	 * @param v
	 * @param text
	 */
	public void setJumpText(TextView v, String text) {

		if (v == null) {
			return;
		}

		v.setText(Html.fromHtml(text, null, null));
		v.setMovementMethod(LinkMovementMethod.getInstance());
		stripUnderlines(v);
	}

	public void setJumpText(TextView v, String text, int textColor) {
		if (v == null) {
			return;
		}

		v.setText(Html.fromHtml(text, null, null));
		v.setMovementMethod(LinkMovementMethod.getInstance());
		stripUnderlines(v, textColor);
	}

	public void stripUnderlines(TextView textView) {
		Spannable s = (Spannable) textView.getText();
		URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
		for (URLSpan span : spans) {
			int start = s.getSpanStart(span);
			int end = s.getSpanEnd(span);
			s.removeSpan(span);
			span = new ALUrlSpan(span.getURL(), this);
			s.setSpan(span, start, end, 0);
			s.setSpan(new BackgroundColorSpan(Color.TRANSPARENT), start, end, 0);
		}
		textView.setText(s);
	}

	public void stripUnderlines(TextView textView, int textColor) {
		Spannable s = (Spannable) textView.getText();
		URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
		for (URLSpan span : spans) {
			int start = s.getSpanStart(span);
			int end = s.getSpanEnd(span);
			s.removeSpan(span);
			span = new ALUrlSpan(span.getURL(), textColor, this);
			s.setSpan(span, start, end, 0);
			s.setSpan(new BackgroundColorSpan(Color.TRANSPARENT), start, end, 0);
		}
		textView.setText(s);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.core.iaj.ALUrlClickListener#onUrlClick(java.lang.String)
	 */
	@Override
	public void onUrlClick(String url) {
		// TODO Auto-generated method stub
		parseClcikUrl(url);
	}

	private void parseClcikUrl(String url) {
		ALUrlClickManager.getALUrlClickManager().startJump(url);
	}

}
